﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TuKu.Common;
using System.IO;
using System.Diagnostics;

namespace TuKu.PPS
{
    public partial class ppsAdd : Form
    {
        bool wselected = false;
        Point p = new Point();
        int driftX = 0, driftY = 0;
        int mx = 0, my = 0;
        // 引用API

        [System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
        public static extern bool BitBlt(
         IntPtr hdcDest, //目标设备的句柄 
         int nXDest, // 目标对象的左上角的X坐标 
         int nYDest, // 目标对象的左上角的X坐标 
         int nWidth, // 目标对象的矩形的宽度 
         int nHeight, // 目标对象的矩形的长度 
         IntPtr hdcSrc, // 源设备的句柄 
         int nXSrc, // 源对象的左上角的X坐标 
         int nYSrc, // 源对象的左上角的X坐标 
         System.Int32 dwRop // 光栅的操作值 
         );
        public Bitmap windowFullScreen()
        {
            //建立屏幕Graphics
            Graphics grpScreen = Graphics.FromHwnd(IntPtr.Zero);
            //根据屏幕大小建立位图
            Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, grpScreen);
            //建立位图相关Graphics
            Graphics grpBitmap = Graphics.FromImage(bitmap);
            //建立屏幕上下文
            IntPtr hdcScreen = grpScreen.GetHdc();
            //建立位图上下文
            IntPtr hdcBitmap = grpBitmap.GetHdc();
            //将屏幕捕获保存在图位中
            BitBlt(hdcBitmap, 0, 0, bitmap.Width, bitmap.Height, hdcScreen, 0, 0, 0x00CC0020);
            //关闭位图句柄
            grpBitmap.ReleaseHdc(hdcBitmap);
            //关闭屏幕句柄
            grpScreen.ReleaseHdc(hdcScreen);
            //释放位图对像
            grpBitmap.Dispose();
            //释放屏幕对像
            grpScreen.Dispose();

            //返回捕获位图
            return bitmap;
        }
        public ppsAdd()
        {
            InitializeComponent();
        }

        private void ppsAdd_Load(object sender, EventArgs e)
        {
            cmburlcate.Items.AddRange(Common.Tag.cncategory);
            //listimg.Items.AddRange(Common.Tag.encategory);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int cateid = cmburlcate.SelectedIndex;
            string catename = Common.Tag.encategory[cateid];
            foreach (string str in listimg.Items)
            {
                MessageBox.Show(str);
            }
        }
        private void dataGridViewArray_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.All;
            }

        }
        private void dataGridViewArray_DragDrop(object sender, DragEventArgs e)
        {
            string[] MyFiles;
            MyFiles = (string[])(e.Data.GetData(DataFormats.FileDrop));
            // 循环处理数组并将文件添加到列表中。
            foreach (string str in MyFiles)
            {
                if (Common.FileManager.checkImgFileExtends(Common.FileManager.getFileExtends(str)))
                {
                    if (!listimg.Items.Contains(str))
                    {
                        listimg.Items.Add(str);
                    }
                }
            }
            //   dataGridViewArray.Items.AddRange(MyFiles);

        }

        private void listimg_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listimg.Items.Count > 1)
            {
                imgShow.Image = Image.FromFile(listimg.Text);
            }
        }
        #region 拖放处理
        private void imgShow_MouseDown(object sender, MouseEventArgs e)
        {
            if (listimg.Items.Count > 0)
            {
                wselected = true;
                p.X = e.X;
                p.Y = e.Y;
            }
        }
        private void imgShow_MouseMove(object sender, MouseEventArgs e)
        {
            if (wselected)
            {
                driftX = p.X - e.X;
                driftY = p.Y - e.Y;
                mx = mx - driftX;
                my = my - driftY;
                Bitmap bm = new Bitmap(this.imgShow.Image);
                Graphics g = imgShow.CreateGraphics();
                g.Clear(imgShow.BackColor);
                g.DrawImage(bm, mx, my);

                p.X = e.X;
                p.Y = e.Y;

                bm.Dispose();
                g.Dispose();

            }
        }
        private void imgShow_MouseUp(object sender, MouseEventArgs e)
        {
            wselected = false;
        }
        #endregion
        private void btnMakeSmall_Click(object sender, EventArgs e)
        {

        }
        private void makeLogo(string fileName)
        {
            Point p = imgShow.PointToScreen(imgShow.Bounds.Location);
            p.Y -= imgShow.Top;
            p.X -= imgShow.Left;
            Rectangle area = new Rectangle(p, new Size(imgShow.Width, imgShow.Height));
            int left = area.Left;
            int right = area.Right;
            int top = area.Top;
            int bottom = area.Bottom;
            if (left < Screen.PrimaryScreen.Bounds.Left)
            { left = Screen.PrimaryScreen.Bounds.Left; }
            if (right > Screen.PrimaryScreen.Bounds.Right)
            { right = Screen.PrimaryScreen.Bounds.Right; }
            if (top < Screen.PrimaryScreen.Bounds.Top)
            { top = Screen.PrimaryScreen.Bounds.Top; }
            if (bottom > Screen.PrimaryScreen.Bounds.Bottom)
            { bottom = Screen.PrimaryScreen.Bounds.Bottom; }
            area.X = left;
            area.Y = top;
            area.Width = right - left;
            area.Height = bottom - top;
            Bitmap bm = new Bitmap(windowFullScreen());
            Image img = bm.Clone(area, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            //            save(img);
            string path = @"d:\pps\upload\baike\tu\upload_img\" + DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString("00");

            if (!System.IO.Directory.Exists(path))
            {
                FileManager.CreateFoler(path);

            }
            System.Drawing.Imaging.ImageFormat imgformat = System.Drawing.Imaging.ImageFormat.Jpeg;
            string fileExtend = listimg.SelectedItem.ToString().getFileExtends().ToLower();
            switch (fileExtend)
            {
                case "jpg":
                    imgformat = System.Drawing.Imaging.ImageFormat.Jpeg;
                    break;
                case "gif":
                    imgformat = System.Drawing.Imaging.ImageFormat.Gif;
                    break;
                default:
                    imgformat = System.Drawing.Imaging.ImageFormat.Jpeg;
                    break;
            }
            //img.Save(path + "\\" + fileName + "." + fileExtend, imgformat);
            Common.WaterMark.myGetThumbnailImage(img, path + "\\" + fileName + "." + fileExtend, 150, 113);
        }
        /// <summary>
        /// 生成展示页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMakeBig_Click(object sender, EventArgs e)
        {
            if (listimg.Items.Count > 2)
            {
                btnMakeBig.Enabled = false;
                MakePic();
                btnMakeBig.Enabled = true;
            }
        }

        private void MakePic()
        {
            //插入主表urltable
            int cateid = cmburlcate.SelectedIndex;
            string titie = txtAlt.Text;
            int pagenumber = listimg.Items.Count;
            int categoryName = int.Parse(Maticsoft.DBUtility.DbHelperOleDb.GetSingle("select top 1  categoryName from urltable order by id desc").ToString()) + 1;
            bool finish = false;
            string url = "http://tu.pps.tv/pics/" + categoryName.ToString() + "/index.html";
            string filename = FileManager.CreateFileName();
            string uri = "http://tujuduo.com/upload/baike/tu/" + DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString("00");
            string path = "d:\\pps\\upload\\baike\\tu\\" + DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString("00");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string picpage = string.Format(uri + "/{0}.jpg", filename);
            if (File.Exists(path + "\\" + filename + ".jpg"))
            {
                File.Delete(path + "\\" + filename + ".jpg");
            }
            File.Copy(listimg.Items[0].ToString(), path + "\\" + filename + ".jpg");
            TuKu.BLL.urltable bll = new TuKu.BLL.urltable();
            TuKu.Model.urltable model = new TuKu.Model.urltable();
            model.categoryid = cateid;
            model.categoryName = categoryName.ToString();
            model.finish = finish;
            model.pagenumber = pagenumber;
            model.picPage = picpage;
            model.title = titie;
            model.url = url;
            bll.Add(model);
            //插入子表urlsubtable
            //主表ID
            int parentid = categoryName;
            TuKu.Model.urlsubtable sub = new TuKu.Model.urlsubtable();
            TuKu.BLL.urlsubtable subBll = new TuKu.BLL.urlsubtable();
            for (int i = 1; i < listimg.Items.Count; i++)
            {
                sub.addtime = DateTime.Now;
                sub.categoryid = cateid;
                sub.currentpage = i + 1;
                sub.picPage = string.Format("http://www.tujuduo.com/upload/baike/tu/" + DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString("00") + "/{0}.jpg", filename + "_" + sub.currentpage.ToString());
                sub.title = titie;
                sub.url = parentid.ToString();
                subBll.Add(sub);
                if (File.Exists(path + "\\" + filename + "_" + sub.currentpage.ToString() + ".jpg"))
                {
                    File.Delete(path + "\\" + filename + "_" + sub.currentpage.ToString() + ".jpg");
                }
                File.Copy(listimg.Items[i].ToString(), path + "\\" + filename + "_" + sub.currentpage.ToString() + ".jpg");
            }
            //生成首页列表LOGO文件
            makeLogo(parentid + "_1");
            //生成首页文件
            int urlcateid = cateid;
            string strTemplate = TuKu.DataAccess.pageMaker.getTemplateByid(8);//展示页模板
            DataTable dtleft = Maticsoft.DBUtility.DbHelperOleDb.Query("select * from urladlist where cateid=1").Tables[0];
            DataTable dtbottom = Maticsoft.DBUtility.DbHelperOleDb.Query("select * from urladlist where cateid=2").Tables[0];
            DataTable urlsubtable = Maticsoft.DBUtility.DbHelperOleDb.Query("select * from urlsubtable where url='" + parentid.ToString() + "'").Tables[0];
            TuKu.DataAccess.pageMaker.makeIndex(parentid, strTemplate, urlcateid, dtleft, dtbottom, urlsubtable);
            //添加到列表页urllist
            string sqllist = " insert into urllist (url,alt,img,orderid,cateid) values ('http://tu.pps.tv/pics/" + parentid.ToString() + "/index.html','" + titie + "','" + "http://www.tujuduo.com/upload/baike/tu/upload_img/" + DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString("00") + "/" + parentid + "_1.jpg',1," + cateid + " )";
            Maticsoft.DBUtility.DbHelperOleDb.ExecuteSql(sqllist);
            btnGetFalse.Visible = true;
            txtAlt.Text = "";
            listimg.Items.Clear();

        }
        private void btnGetFalse_Click(object sender, EventArgs e)
        {
            string strsql = " select top 1 id from urltable where pagenumber = -1 and finish = 0 ";
            string id = Maticsoft.DBUtility.DbHelperOleDb.GetSingle(strsql).ToString();
            TuKu.Model.urltable model = new TuKu.BLL.urltable().GetModel(int.Parse(id));
            txtAlt.Text = model.title;
            linkLabel1.Text = model.url;
            linkLabel1.Click += new EventHandler(linkLabel1_Click);
            strsql = "update urltable set finish=1 where id=" + model.id.ToString();
            Maticsoft.DBUtility.DbHelperOleDb.ExecuteSql(strsql);
            btnGetFalse.Visible = false;
        }

        void linkLabel1_Click(object sender, EventArgs e)
        {
            using (Process p = new Process())
            {
                if (File.Exists("D:\\Maxthon2\\Maxthon.exe"))
                {
                    p.StartInfo.FileName = "D:\\Maxthon2\\Maxthon.exe";
                }
                else
                {
                    p.StartInfo.FileName = "IEXPLORE.EXE";
                }
                p.StartInfo.Arguments = "http://images.google.cn/images?hl=zh-CN&q=" + txtAlt.Text;
                p.Start();
            }

        }

        private void ppsAdd_Activated(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(Clipboard.GetText()))
                txtAlt.Text = Clipboard.GetText();
        }

        private void ppsAdd_Enter(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(Clipboard.GetText()))
                txtAlt.Text = Clipboard.GetText();
        }

        private void ppsAdd_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(Clipboard.GetText()))
                txtAlt.Text = Clipboard.GetText();
        }

        private void btnSiteMap_Click(object sender, EventArgs e)
        {
            DataTable dt = Maticsoft.DBUtility.DbHelperOleDb.Query("select * from urllist").Tables[0];
            StringBuilder sb = new StringBuilder();
            //int i = 1;
            sb.Append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n");
            sb.Append("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\r\n");
            foreach (DataRow dr in dt.Rows)
            {
                //http://www.tujuduo.com/pics/78946/index.html
                //http://tu.pps.tv/pics/71245/index.html
                sb.Append("<url><loc>" + dr["url"].ToString().Replace("tu.pps.tv", "www.tujuduo.com") + "</loc><lastmod>" + DateTime.Parse(dr["addtime"].ToString()).ToString("yyyy-MM-dd") + "</lastmod><changefreq>monthly</changefreq><priority>0.5</priority></url>\r\n");
                //i++;
                //if (i==40000 || i==80000 || i==120000)
                //{
                //    FileManager.WriteFile("c:\\Sitemap"+i.ToString()+".xml", sb.ToString());
                //    sb.Remove(0, sb.Length);
                //}
                
            }
            sb.Append("</urlset>");
            FileManager.WriteFile("c:\\Sitemap5.xml", sb.ToString());
            MessageBox.Show("ok");
        }


    }
}
